/* 
 * Fichier javascript pour le bloc image
 * dans Fo : ajout annonnce
 */


     $(function(){
          
        var item = '';
        var delSrc = '';
        var noImage = $('#noImage').val();
        if(document.getElementById('accordion'))  $("#accordion").accordion({autoHeight: false,collapsible: true});
       if(document.getElementById('accordion2')) $("#accordion2").accordion({autoHeight: false,collapsible: true});
       
       
        function countImage () {
            nbr = 0;
            if ($.trim($('.infiniteCarousel ul').html()) == "") return 0;
            $('.infiniteCarousel li').each(function () {
                cl = $(this).attr('class');
                if(cl && (cl.indexOf('empty') == -1) && (cl.indexOf('cloned') == -1) ) nbr++;
            });

            return nbr + 1;
        }
        
        //chargement dynamique des modeles en fonctions de la marque choisie
        $("#ess_iMarqueId").change(function(){
            var zUrlModel1 = $('#urlLoadModele').val();
            if ($(this).val() != ""){

                $.getJSON(zUrlModel1,{iMarqueId: $(this).val()}, function(result){
                zoptions = '';
                size = result.length;

                for (i = 0; i < size; i++) {
                    zoptions += '<option value="' + result[i].modele_id + '">' + result[i].modele_libelle + '</option>';
                }
                $("#ess_iModelId").html(zoptions);
                });
            }else {
                $("#ess_iModelId").html("<option value=''>Modeles</option>");
            }
        });
        
       

        //commentaires limité à 90 carctères
        $(".comment").keyup(function(){
            var content = $(this).val();
            if(content.length <= 90){
                    $("#cptr").val(90 - content.length);
            } else {
                $("#cptr").val(0);
                $(this).val(content.substring(0, 90));
            }
        });

        function searchInArray(val,tab){
            var len = tab.length;
            for(i=0;i<len;i++){
                if(tab[i] == val) {
                    return true; 
                }
            }return false;
        }
        
        
        
       function hideOrShowIfEmpty(ul,div){
           var contenu = $.trim($(ul).html());
            if (contenu == ""){
                $(div).hide();
            } else {
                $(div).show();
            }
       }
       
       
           
       function initPP(src){
           var forPop = '';
            var tab = new Array(10);    
            $('.infiniteCarousel li img:not(.deleteImage)').each(function(){
                    var src2 = $(this).attr('src');
                    if ( (src2 != src) &&(!searchInArray(src2,tab))) {
                        tab.push(src2);
                        forPop += '<a href="' + src2 + '" rel="prettyPhoto[pp_gal]" title="'+ src2 + '">';
                        forPop += '<img src="' + src2 + '" width="60" height="60" alt="'+ src2 + '" /> </a> ';
                    }
                });
           $('#forPopUp').html(forPop);
            $(".showPP").attr('href',src);
            $(".showPP img").attr('alt',src);
            $("a[rel^='prettyPhoto']").prettyPhoto({
                social_tools: ''
            });
       }
        
        function initCarousel(){
            
             $('.infiniteCarousel').infiniteCarousel();
            hideOrShowIfEmpty('.infiniteCarousel ul','.infiniteCarousel');
            $('.infiniteCarousel li img:not(.deleteImage)').bind('click', function() {
                var src = $(this).attr('src');
                $('#ap_img').fadeOut(300, function() {
                    $(this).attr('src',src);
                }).fadeIn(300);
                //majCoordShowPP($(this).height());
                $('.showPP').attr('rel','prettyPhoto[pp_gal]');
                initPP(src);
            });
            $("a[rel^='prettyPhoto']").prettyPhoto({
                    social_tools: ''
            });
                
            $('.deleteImage').click(function(){
                
                var toDel = $(this).prev().attr('src');
                if ($(this).prev().attr('class') == 'photo_princ') {
                    $('#thumb').attr('src',noImage);
                    $('#fic_princ').val('');
                }
                var tab = new Array(10);
                var appercu = '';
                var forPop = '';
                var html  = '<div class="wrapper"><ul>';
                var photo_annonce = '';
                h = 0;
                $('.infiniteCarousel li img:not(.deleteImage)').each(function(){
                    var src2 = $(this).attr('src');
                    if ( (src2 != toDel) &&(!searchInArray(src2,tab))) {
                        tab.push(src2);
                        var tabSrc = src2.split('/');
                        appercu = $(this).attr('src')
                        h = $(this).height();
                        html += '<li><img src="'+src2+'" ';
                        if ($(this).attr('class') == 'photo_princ') {
                            html += ' class="photo_princ"';
                        } else{
                            photo_annonce += (photo_annonce == '') ? tabSrc[tabSrc.length -1] : ',' +  tabSrc[tabSrc.length -1];
                        }
                        html += 'title="'+src2+'" width="84" /><img src="' + delSrc +'" class="deleteImage" title="Supprimer cette image" /></li>';
                        forPop += '<a href="' + src2 + '" rel="prettyPhoto[pp_gal]" title="'+ src2 + '">';
                        forPop += '<img src="' + src2 + '" width="60" height="60" alt="'+ src2 + '" /> </a> ';
                        
                    }
                });
                $('#photo-annonce').val(photo_annonce);
                html += '</ul></div>';
                $('.infiniteCarousel').html(html);
                $('#forPopUp').html(forPop);
                $('#forPopUp a:last').remove();
                $('.showPP').attr('rel','prettyPhoto[pp_gal]');
                $(".showPP").attr('href',appercu);
                $(".showPP img").attr('alt',appercu);
                initCarousel();
                $('#ap_img').attr('src',appercu);
                //majCoordShowPP($('#ap_img').height());
            });
        }
        
            $('#status_fic').hide();
            $('#status_supp').hide();
            //mecanisme file upload fichier principal
            var path = $('#path_min').val();
            var btnUpload=$('#upload');    
            new AjaxUpload(btnUpload, {  
                action: zUrlUpload,  
                //Name of the file input box  
                name: 'uploadfile',  
                onSubmit: function(file, ext){  
                    if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext))){  
                        // check for valid file extension  
                        alert('Only JPG, PNG or GIF files are allowed');  
                        return false;  
                    }
                    $('#status_fic p').html("Chargement de : " + file);
                    $('#status_fic').show();
                },  
                onComplete: function(file, response){
                    //On completion clear the status  
                    $('#status_fic').hide();

                    //Add uploaded file to list
                    if(response.search('success') != -1 ){  
                        
                        var name = file.split(".");
                            $('#fic_princ').val(file);
                            $('#thumb').attr('src',path + file);
                            var tab = new Array(10);
                            var html  = '<div class="wrapper"><ul>';
                            var forPop = '';
                            var cptr = 1;
                            var photo_annonce = $('#photo-annonce').val();
                            html += '<li><img src="'+path + file+'" class="photo_princ" title="' + file+'"  width="84" /><img src="'+delSrc+'" class="deleteImage" title="Supprimer cette image" /></li>';
                            $('.infiniteCarousel li img:not(.deleteImage):not(.photo_princ)').each(function(){
                                var src2 = $(this).attr('src');
                                if (!searchInArray(src2,tab)) {
                                    tab.push(src2);
                                    cptr++;
                                    html += '<li><img src="'+$(this).attr('src')+'" title="'+$(this).attr('src')+'" width="84" /><img src="'+delSrc+'" class="deleteImage" title="Supprimer cette image" /></li>';
                                    forPop += '<a href="' + $(this).attr('src') + '" rel="prettyPhoto[pp_gal]" title="'+ $(this).attr('src') + '">';
                                    forPop += '<img src="' + $(this).attr('src') + '" width="60" height="60" alt="'+ $(this).attr('src') + '" /> </a> ';
                                }
                            });
                            html += '</ul></div>';
                            
                           // photo_annonce += (photo_annonce == '') ? file : ',' + file;
                            $('#photo-annonce').val(photo_annonce);
                            $('.infiniteCarousel').html(html);
                            $('.infiniteCarousel').show();
                            $('#ap_img').attr('src',path + file);
                            //majCoordShowPP($('#ap_img').height());
                            $('#forPopUp').html(forPop);
                            $(".showPP").attr('href',path+file);
                            $(".showPP img").attr('alt',file);
                            initCarousel();
                            
                    }
                }  
            });
                
            //mecanisme file upload fichier supplémentaire
            var btnUpload=$('#upload_supp');  
            new AjaxUpload(btnUpload, {  
                action: zUrlUpload,  
                //Name of the file input box  
                name: 'uploadfile',  
                onSubmit: function(file, ext){  
                    if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext))){  
                        // check for valid file extension  
                        alert('Only JPG, PNG or GIF files are allowed');  
                        return false;  
                    }  
                    $('#status_supp p').html("Chargement de : " + file);
                    $('#status_supp').show();  
                },  
                onComplete: function(file, response){
					//alert(file) ;
                    //On completion clear the status  
                    $('#status_supp').hide();  

                    //Add uploaded file to list
                    if(response.search('success') != -1 ){
                        //console.log(countImage());
                        if (countImage() > 10){
                            alert('Vous ne pouvez plus ajouter des images supplémentaires. Merci');

                        } else {
                            var name = file.split(".");
                            $('#fic_supp').val(file);
                            $('#thumb_supp').attr('src',path + file);
                            var tab = new Array(10);
                            var html  = '<div class="wrapper"><ul>';
                            var forPop = '';
                            var cptr = 1;
                            var photo_annonce = $('#photo-annonce').val();
                            $('.infiniteCarousel li img:not(.deleteImage)').each(function(){
                                var src2 = $(this).attr('src');
                                if (!searchInArray(src2,tab)) {
                                    tab.push(src2);
                                    cptr++;
                                    html += '<li><img src="'+$(this).attr('src')+'" ';
                                    var fp = $(this).attr('class');
                                    if(fp && (fp == 'photo_princ')) html += ' class="photo_princ" ';
                                    html += 'title="'+$(this).attr('src')+'" width="84" /><img src="'+delSrc+'" class="deleteImage" title="Supprimer cette image" /></li>';
                                    forPop += '<a href="' + $(this).attr('src') + '" rel="prettyPhoto[pp_gal]" title="'+ $(this).attr('src') + '">';
                                    forPop += '<img src="' + $(this).attr('src') + '" width="60" height="60" alt="'+ $(this).attr('src') + '" /> </a> ';
                                }
                            });
                            html += '<li><img src="'+path + file+'"  title="' + file+'"  width="84" /><img src="'+delSrc+'" class="deleteImage" title="Supprimer cette image" /></li></ul></div>';
                            
                            photo_annonce += (photo_annonce == '') ? file : ',' + file;
                            $('#photo-annonce').val(photo_annonce);
                            $('.infiniteCarousel').html(html);
                            $('.infiniteCarousel').show();
                            $('#ap_img').attr('src',path + file);
                            //majCoordShowPP($('#ap_img').height());
                            $('#forPopUp').html(forPop);
                            $(".showPP").attr('href',path+file);
                            $('.showPP').attr('rel','prettyPhoto[pp_gal]');
                            $(".showPP img").attr('alt',file);
                            initCarousel();
                        }
                    }
                }  
            });
            initCarousel();
            delSrc = $('#delImage').val();
            $('#thumb').bind('click', function() {
                var src = $(this).attr('src');
                var tabSrc = src.split('/');
                if(tabSrc[tabSrc.length - 1] != 'no_image.jpg'){
                    $('#ap_img').fadeOut(300, function() {
                        $(this).attr('src',src);
                    }).fadeIn(300);
                    initPP(src);
                }
                //majCoordShowPP($(this).height());
                
            });
            $('#thumb_supp').bind('click', function() {
                var src = $(this).attr('src');
                var tabSrc = src.split('/');
                if(tabSrc[tabSrc.length - 1] != 'no_image.jpg'){
                    $('#ap_img').fadeOut(300, function() {
                        $(this).attr('src',src);
                    }).fadeIn(300);
                    initPP(src);
                }
                //majCoordShowPP($(this).height());
            });
            
            
        });


